#include "NetworkClientConnection.h"

#include <iostream>

#include "EventEngine.h"
#include "IGameEvent.h"

using namespace ENE;

NetworkClientConnection::NetworkClientConnection()
: m_ioService(), m_clientSession(m_ioService)
{

}

void NetworkClientConnection::setId(Int8 id)
{
	m_id = id;
}

Int8 NetworkClientConnection::getId() const
{
	return m_id;
}

void NetworkClientConnection::connect(const std::string& host, const std::string& port)
{
	ClientSession::ConnectCallback connectCallback;
	connectCallback = boost::bind(&NetworkClientConnection::handleConnect, this, boost::asio::placeholders::error);
	m_clientSession.connect(host, port, connectCallback);
}

void NetworkClientConnection::handleConnect(const boost::system::error_code& error)
{
	std::cout << "Client: Connecte" << std::endl;

	ENE::SocketConnection::ReadCallback handshakeCallback;
	handshakeCallback = boost::bind(&NetworkClientConnection::handleHandshakeRead, this, boost::asio::placeholders::error, _2);
	m_clientSession.read(handshakeCallback);
}

void NetworkClientConnection::handleHandshakeRead(const boost::system::error_code& error, const std::vector<Int8>& data)
{
	if(error)
	{
		std::cout << error.message() << std::endl;
	}
	else
	{
		Int8 clientId = data[0];
		std::string msg(data.begin(),data.end());
		setId(clientId);
	}
}

void NetworkClientConnection::start()
{
	m_serviceThread = boost::thread(boost::bind(&boost::asio::io_service::run, &m_ioService));
}

void NetworkClientConnection::sendEvent(boost::shared_ptr<const IGameEvent> event)
{
	std::string data = event->serialize();
	m_clientSession.write(data);
}

void NetworkClientConnection::setEventEngine(boost::shared_ptr<EventEngine> eventEngine)
{
	m_eventEngine = eventEngine;
}